package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = (Page<DishVO>)dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = Dish.builder()
                .id(dishDTO.getId())
                .name(dishDTO.getName())
                .categoryId(dishDTO.getCategoryId())
                .price(dishDTO.getPrice())
                .description(dishDTO.getDescription())
                .image(dishDTO.getImage())
                .status(dishDTO.getStatus())
                .updateTime(LocalDateTime.now())
                .createTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        // 修改菜品
        dishMapper.update(dish);
        Long dishId = dish.getId();
        //如果有口味就删除
        if (dishDTO.getFlavors().size() > 0 && dishDTO.getFlavors() != null){
            dishFlavorMapper.delete(dishId);
        }
        //添加新的口味
        for (DishFlavor flavor : dishDTO.getFlavors()) {
            flavor.setDishId(dishId);
            dishFlavorMapper.saveFlavor(flavor);
        }
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        DishVO byId = dishMapper.getById(id);
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
        byId.setFlavors(flavors);
        return byId;
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    public void delete(List<Integer> ids) {
        if (ids.size() > 0 && ids != null){
            for (Integer id : ids) {
                Long idLong = Long.valueOf(id);
                DishVO dish = dishMapper.getById(idLong);
                if (dish.getStatus() == 1){
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
            }
        }
        ids.forEach(id -> {
            Long idLong = Long.valueOf(id);
            Integer dish = setmealMapper.contById(idLong);
            if (dish > 0 && dish != null){
                //判断菜品是否被套餐关联
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });
        //根据ids集合批量删除菜品
        dishMapper.delete(ids);
    }

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    //事务
    @Transactional
    public void save(DishDTO dishDTO) {
        Dish dish = Dish.builder()
                .name(dishDTO.getName())
                .categoryId(dishDTO.getCategoryId())
                .price(dishDTO.getPrice())
                .description(dishDTO.getDescription())
                .image(dishDTO.getImage())
                .status(dishDTO.getStatus())
                .build();
        dishMapper.save(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors.size() > 0 && flavors != null){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
                dishFlavorMapper.saveFlavor(flavor);
            }
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(Integer categoryId) {
        return dishMapper.list(Long.valueOf(categoryId));
    }

    /**
     * 启停
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        dishMapper.startOrStop(status,id);
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        log.info(dish.toString());
        List<DishVO> dishList = dishMapper.list(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (DishVO d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

//    /**
//     * 根据分类id查询菜品
//     * @param categoryId
//     * @return
//     */
//    @Override
//    public List<Dish> list(Long categoryId) {
//        return dishMapper.list(categoryId);
//    }
}
